<template>
  <div class="tem-table">
    <div class="top-header">
      <el-input style="width: 260px" v-model="filterText" placeholder="关键词搜索"/>
      &nbsp;
      <el-button type="primary" @click="HaneleaddTree()">添加根菜单</el-button>
      &nbsp;
      <el-button type="info" @click="onExportSettings()">导出配置</el-button>
    </div>
    <div class="tree-box">
      <el-tree
          :data="dataSource"
          :show-checkbox="false"
          ref="treeRef"
          node-key="id"
          v-loading="loading"
          default-expand-all
          :filter-node-method="filterNode"
          :props="{label: 'title'}"
          :expand-on-click-node="false"
          :indent="30"
      >
        <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span :class="data.status?'active-color':'inactive-color'">{{ data.title }}</span>
                <span>
                  <a style="color: #1a9537" @click="append(data)">&nbsp;新增子节点&nbsp;</a>
                  &nbsp;
                  <a style="color: #2c75e6" @click="edit(data)">&nbsp;编辑节点&nbsp;</a>
                  &nbsp;
                  <a style="color: #006600" @click="remove(data)">&nbsp;删除节点&nbsp;</a>
                </span>
              </span>
        </template>
      </el-tree>
    </div>
  </div>
  <el-dialog
      v-model="menuAddDialogVisible"
      title="编辑菜单"
      width="500px"
      destroy-on-close
  >
    <el-form :model="addForm" :rules="rules" ref="Formel" label-width="120px">
      <el-form-item label='权限标识符' prop="symbolStr">
        <el-input v-model="addForm.symbolStr" placeholder="比如 user" style="width: 300px" clearable></el-input>
      </el-form-item>
      <el-form-item label="菜单名称" prop="title">
        <el-input v-model="addForm.title" placeholder="比如 用户管理" style="width: 300px" clearable></el-input>
      </el-form-item>
      <el-form-item label="RouteUrl" prop="pathUrl">
        <el-input v-model="addForm.pathUrl"
                  placeholder="请输入路由路径"
                  style="width: 300px" clearable></el-input>
      </el-form-item>
      <el-form-item label="Component" prop="pathUrl">
        <el-input v-model="addForm.component" placeholder="请输入项目component文件路径"
                  style="width: 300px" clearable></el-input>
      </el-form-item>
      <el-form-item label="菜单Icon" prop="icon">
        <el-input v-model="addForm.icon" placeholder="比如 ./assert/user.png" style="width: 300px" clearable></el-input>
      </el-form-item>
      <el-form-item label="菜单参数" prop="params">
        <el-input v-model="addForm.params" placeholder="比如 uid=123&name=xiaoming" style="width: 300px"
                  clearable></el-input>
      </el-form-item>
      <el-form-item label="排序字段" prop="idx">
        <el-input v-model.number="addForm.idx" placeholder="比如 1、11、112" style="width: 300px" clearable></el-input>
      </el-form-item>
      <el-form-item label="启用状态" prop="status">
        <el-switch v-model="addForm.status" :active-value="1" :inactive-value="0"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="menuAddDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addMenu(Formel)">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {onMounted, watch, nextTick} from "vue";
import {
  ElMessage,
  ElMessageBox,
  type ElTree,
  type FormInstance,
} from 'element-plus';

import {
  adminGetAppList,
  delMenu, editMenu,
  EditMenuArgs, exportAppSettingsInsertSql, getAppMenuList
} from '@/service/AppManager';
import type {MenuMo} from '@/service/entity/MenuMo';
import {AppMo} from "@/service/entity/AppMo";

const props = defineProps<{
  appId: any
}>()
//添加编辑dialog
const menuAddDialogVisible = ref(false)
const loading = ref(false)
//新增应用菜单
const TreeSelect = ref<any>(null)
const Formel = ref<FormInstance>()
const addForm = reactive<EditMenuArgs>({
  appId: undefined,
  icon: undefined,
  symbolStr: '',
  menuId: undefined,
  parentId: undefined,
  pathUrl: '',
  component: '',
  title: '',
  idx: 0,
  params: '',
  status: 1
})
const dataSource = ref<MenuMo[]>([])
const treeRef = ref<InstanceType<typeof ElTree>>()
const filterText = ref('')
const rules = reactive({
  title: [{required: true, message: ' 名称为必填项', trigger: 'blur'}],
})
const appDetail = ref<AppMo>()
//添加--应用菜单
onMounted(async () => {
  await updata()

  const res1 = await adminGetAppList({id: props.appId})
  appDetail.value = res1.arr[0]
})

watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
//添加--应用菜单
const addMenu = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      addForm.appId = props.appId
      const res = await editMenu(addForm)
      if (res) {
        formEl.resetFields()
        updata()
        menuAddDialogVisible.value = false
        ElMessage({
          type: 'success',
          message: '已提交'
        })
        return true
      } else {
        return false
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}
const updata = async () => {
  loading.value = true
  try {
    const res = await getAppMenuList(props.appId)
    nextTick((() => {
      dataSource.value = res.arr
    }))
  } finally {
    setTimeout(() => loading.value = false, 200)
  }


}
const append = (data: { [x: string]: any; }) => {
  HaneleaddTree(data.id)
}

//添加处理
const HaneleaddTree = (id) => {
  addForm.parentId = id
  addForm.appId = props.appId
  addForm.icon = undefined
  addForm.symbolStr = ''
  addForm.menuId = undefined
  addForm.pathUrl = ''
  addForm.component = ''
  addForm.title = ''
  addForm.idx = 0
  addForm.params = ''
  addForm.status = 1
  menuAddDialogVisible.value = true
}


const edit = (data: MenuMo) => {
  for (let key in data) {
    addForm[key] = data[key]
  }
  addForm.appId = props.appId
  addForm.menuId = data.id
  menuAddDialogVisible.value = true
}
const remove = async (data: any) => {
  ElMessageBox.confirm(
      '永久删除该条信息. 是否确认?',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    const res = await delMenu(data.id)
    if (res) {
      updata()
    }
  })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}

//搜索树
const filterNode = (value, data) => {
  if (!value) return true
  return `${data.title}-${data.symbolStr}`.includes(value)
}

const onExportSettings = async () => {
  await exportAppSettingsInsertSql(props.appId,localStorage.getItem('appName'));
}

</script>


<style scoped lang="scss">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 16px;
  padding: 10px 0px;
  padding-right: 8px;

  .active-color {
    color: green;
  }

  .inactive-color {
    color: #999;
  }
}

.tem-table {
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  padding: 10px;

  .tree-box {
    width: 600px;
    flex: 1;
    overflow: auto;
  }


  .top-header {
    display: flex;
    justify-content: flex-end;

    .tree-input {
      flex: 1;
      align-items: center;
    }
  }
}


.tree-header-title {
  display: inline-block;
  padding: 0 10px;
  line-height: 2;
  text-align: center;
  vertical-align: middle;
}
</style>